package com.taxshare.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taxshare.api.constant.CommonConstant;
import com.taxshare.api.view.dto.InterfaceDTO;
import com.taxshare.api.view.dto.SellerInvoiceDTO;
import com.taxshare.api.view.dto.WriteBackInvoiceDTO;
import com.taxshare.api.view.vo.InterfaceVO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.util.Base64Util;
import com.taxshare.tools.util.SignUtil;
import com.taxshare.tools.util.XmlInterfaceUtils;
import com.taxshare.tools.util.sst.HttpUtil;
import com.taxshare.tools.util.sst.RequestKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
public class SellerInvoiceService {

    @Value("${purchaser.appid}")
    private String appid;

    @Value("${purchaser.appsecret}")
    private String appsecret;

    @Value("${purchaser.jtnsrsbh}")
    private String jtnsrsbh;

    @Value("${purchaser.url}")
    private String url;

    @Value("${purchaser.autoHead}")
    private String autoHead;

    @Value("${sst.sstUrl}")
    private String sstUrl;

    @Value("${sst.privateKey}")
    private String privateKey;

    @Value("${sst.publicKey}")
    private String publicKey;

    @Value("${writeBackInvoice.url}")
    private String writeBackInvoiceUrl;

    @Value("${syncProjectInfo.url}")
    private String syncProjectInfoUrl;

    @Autowired
    RestTemplate customRest;

    public Response callSST(SellerInvoiceDTO sellerInvoiceVo) {
        Response response = new Response();
        String bw = sellerInvoiceVo.getBw();
        log.info("接收的销项报文为：" + bw);
        try {
            JSONObject ret = RequestKit.request(sstUrl, publicKey, privateKey, bw);
            response.setData(ret.toString());
        } catch (Exception e) {
            log.info("请求税神通报错：" + e.getMessage());
            response.setCode("T0001");
        }

        return response;
    }

    /**
     * 调用销项接口
     *
     * @param interfaceDTO
     * @return
     */
    public Response callSales(InterfaceDTO interfaceDTO) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/xml;charset=UTF-8");
        HttpEntity<String> entity = new HttpEntity<String>(interfaceDTO.getXmlData(), headers);
        ResponseEntity<String> response = customRest.postForEntity(interfaceDTO.getUrl(), entity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            String rjxml = response.getBody();
            InterfaceVO interfaceVO = (InterfaceVO) XmlInterfaceUtils.XmltoBean(rjxml, InterfaceVO.class);
            String returnCode = interfaceVO.getReturnStateInfo().getReturnCode();
            String zipCode = interfaceVO.getData().getDataDescription().getZipCode();
            String returnMessage = Base64Util.decode(interfaceVO.getReturnStateInfo().getReturnMessage());
            if (returnCode.equals("0000")) {
                String reqcontent = interfaceVO.getData().getContent();
                if("1".equals(zipCode)){
                    byte[] decodeBase64 = org.apache.commons.codec.binary.Base64.decodeBase64(reqcontent.getBytes(StandardCharsets.UTF_8));
                    reqcontent = new String(cn.hutool.core.util.ZipUtil.unGzip(decodeBase64));
                }else {
                    reqcontent = Base64Util.decode(interfaceVO.getData().getContent());
                }
                return Response.success(reqcontent);
            } else {
                return Response.error(returnCode, returnMessage);
            }
        } else {
            return Response.error("" + response.getStatusCode(), "接口调用异常");
        }
    }

    public Response autoHead(SellerInvoiceDTO sellerInvoiceVo) {
        Map<String, String> querys = new HashMap<>();
        querys.put("appid", CommonConstant.APPID);
        querys.put("serviceid", "S000706");
        querys.put("jtnsrsbh", CommonConstant.JT_SH);
        querys.put("nsrsbh", CommonConstant.JT_SH);//该字段  参数名要有，值可以为空

        JSONObject contentMap = new JSONObject();
        contentMap.put("taxname", sellerInvoiceVo.getGfmc());//要查询的企业名称
        //log.info("contentMap====" + contentMap);
        String content = Base64Util.encode(contentMap.toString());
        querys.put("content", content);
        String signR = SignUtil.signs(CommonConstant.SIGN_TYPE, CommonConstant.APPSCERT, querys);
        querys.put("signature", signR);
        querys.put("signType", CommonConstant.SIGN_TYPE);
        //log.info("querys====" + querys);
        Long before = System.currentTimeMillis();
        Map<String, String> result = HttpUtil.post(CommonConstant.SST_URL, querys);
        //log.info("result===" + result);
        Long after = System.currentTimeMillis();
        log.info("===获取抬头信息花费时间==" + (after - before));
        ObjectMapper json = new ObjectMapper();
        try {
            String params = json.writeValueAsString(result);
            JSONObject jobo = JSON.parseObject(params);
            JSONObject jobo2 = JSON.parseObject(jobo.getString("response"));
            String contentq = jobo2.getString("content");
            String body = decodeBase64(contentq);
            JSONArray jsonArray = JSON.parseArray(body);
            return Response.success(jsonArray);
        } catch (JsonProcessingException e) {
            log.info("请求只能抬头异常" + e.getMessage());
            return Response.error(e.getMessage());
        }

    }

    public static String decodeBase64(String str) {
        Base64.Decoder decoder = Base64.getDecoder();
        String decode = null;
        try {
            decode = new String(decoder.decode(str), "utf-8");
        } catch (Exception e) {
        }
        return decode;
    }

    /**
     * 回传开票信息给明源
     *
     * @param writeBackInvoiceDTO
     * @return
     */
    public Response writeBackIncoice(WriteBackInvoiceDTO writeBackInvoiceDTO) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        map.add("VouchGUID",writeBackInvoiceDTO.getVouchGUID());
        map.add("VatNo",writeBackInvoiceDTO.getVatNo());
        map.add("VatStatus",writeBackInvoiceDTO.getVatStatus());
        map.add("Key",writeBackInvoiceDTO.getKey());
        HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(writeBackInvoiceUrl,requestParams,String.class);
        String result =response.getBody();
        return Response.success(result);
    }

    /**
     * 同步明源项目信息
     *
     * @return
     */
    public Response syncProjectInfo() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.postForEntity(syncProjectInfoUrl, requestParams, String.class);
        String result = response.getBody();
        return Response.success(result);
    }

}
